package org.web.clientlistmanager.sdk.event;

import com.google.gson.Gson;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.CharsetUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.web.base.domain.helper.ServiceExceptionHelper;
import org.web.clientlistmanager.sdk.dto.ClmRequest;

import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

public class EventHelper {

    private static final Logger logger = LogManager.getLogger(EventHelper.class);

    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private static Gson gson = new Gson();
    private static final String SEPARATE = "@S@";

    public static ByteBuf transClmRequest2Byte(ClmRequest clmRequest) {
        return Unpooled.copiedBuffer(SEPARATE + gson.toJson(clmRequest), CharsetUtil.UTF_8);
    }

    public static List<ClmRequest> parseRequest(Object msg) {
        ByteBuf bb = (ByteBuf) msg;
        // 创建一个和buf同等长度的字节数组
        byte[] reqByte = new byte[bb.readableBytes()];
        // 将buf中的数据读取到数组中
        bb.readBytes(reqByte);
        String reqStr = new String(reqByte, StandardCharsets.UTF_8);
        List<ClmRequest> list = new ArrayList<>();
        String[] array = reqStr.split(SEPARATE);
        for (String value : array) {
            try {
                ClmRequest clmRequest = gson.fromJson(value, ClmRequest.class);
                if(clmRequest !=null){
                    list.add(clmRequest);
                }
            } catch (Exception e) {
                logger.error(ServiceExceptionHelper.getExceptionInfo(e));
            }
        }
        return list;
    }

    public static ChannelFuture sendClmRequest(Channel channel, ClmRequest clmRequest){
        defaultExecute(clmRequest);
        return channel.writeAndFlush(EventHelper.transClmRequest2Byte(clmRequest));
    }

    public static ChannelFuture sendClmRequest(ChannelHandlerContext ctx, ClmRequest clmRequest){
        defaultExecute(clmRequest);
        return ctx.writeAndFlush(EventHelper.transClmRequest2Byte(clmRequest));
    }

    private static void defaultExecute(ClmRequest clmRequest){
        clmRequest.setRequestId(UUID.randomUUID().toString());
        clmRequest.setSendTime(DATE_FORMAT.format(new Date()));
    }

}
